import routes from './routes';
import { normalizeLink, isCurrentUrl, history } from './helper/history';
import axios from 'axios';

function responseAdptor(ret) {
  if (!ret.data) {
    return {
      status: -1,
      msg: '请求失败',
    };
  }
  if (ret.data.code == 200) {
    return {
      status: 0,
      msg: ret.data.message,
      data: ret.data.data,
    };
  }
  return {
    status: ret.data.code,
    msg: ret.data.message,
    data: ret.data,
  };
}
function initApp() {
  let amis = amisRequire('amis/embed');
  // 如果想用 browserHistory 请切换下这处代码, 其他不用变
  // const history = History.createBrowserHistory();
  const app = {
    type: 'app',
    brandName: '后台管理系统',
    logo: 'https://uviewui.com/common/logo.png',
    header: {
      type: 'tpl',
      inline: false,
      className: 'w-full',
      tpl: `
      <div class="flex justify-between">
        <div>顶部区域左侧</div>
        <div>顶部区域右侧</div>
      </div>
      `,
    },
    // footer: '<div class="p-2 text-center bg-light">底部区域</div>',
    // asideBefore: '<div class="p-2 text-center">菜单前面区域</div>',
    // asideAfter: '<div class="p-2 text-center">菜单后面区域</div>',
    ...routes,
  };

  let amisInstance = amis.embed(
    '#root',
    app,
    {
      location: history.location,
      data: {
        // 全局数据，是受控的数据
      },
      context: {
        // 全局上下文数据, 非受控的数据，无论哪一层都能获取到，包括弹窗自定义数据映射后都能获取到。
        // 可以用来放一下全局配置等。比如 API_HOST, 这样页面配置里面可以通过 ${API_HOST} 来获取到。
        API_HOST: 'https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com',
      },
    },
    {
      fetcher: ({
        url, // 接口地址
        method, // 请求方法 get、post、put、delete
        data, // 请求数据
        responseType,
        config, // 其他配置
        headers, // 请求头
      }) => {
        config = config || {};
        config.withCredentials = true;
        responseType && (config.responseType = responseType);

        if (config.cancelExecutor) {
          config.cancelToken = new axios.CancelToken(config.cancelExecutor);
        }

        config.headers = headers || {
          authorization:
            'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc0FkbWluIjp0cnVlLCJjcmVhdGVkQXQiOiIyMDI1LTA1LTI1IDA5OjM4OjIyIiwidXBkYXRlZEF0IjoiMjAyNS0wNS0yNSAwOTozODoyMiIsImRlbGV0ZWRBdCI6bnVsbCwiaWQiOjEsImVtYWlsIjoiMTIxNjE4MTA2N0BxcS5jb20iLCJ1c2VyTmFtZSI6InN1cGVyIiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsIm5pY2tOYW1lIjoi6LaF57qn566h55CG5ZGYIiwidGVsIjoiMTM2NjY2NjY2NiIsImdlbmRlciI6MSwic3RhdHVzIjoxLCJ0eXBlIjoiYWRtaW5fdXNlciIsInJlbWFyayI6bnVsbCwiYXZhdGFyIjoiaHR0cHM6Ly91dmlld3VpLmNvbS9jb21tb24vbG9nby5wbmciLCJpYXQiOjE3NDgxNjU5NDUsImV4cCI6MTc1MDc1Nzk0NX0.K5kVpyPn64iiryXjJ9Z6-7njQNgICffqHqssehnRGVw',
        };

        if (method !== 'post' && method !== 'put' && method !== 'patch') {
          if (data) {
            config.params = data;
          }

          return axios[method](url, config).then(responseAdptor);
        } else if (data && data instanceof FormData) {
          config.headers = config.headers || {};
          config.headers['Content-Type'] = 'multipart/form-data';
        } else if (
          data &&
          typeof data !== 'string' &&
          !(data instanceof Blob) &&
          !(data instanceof ArrayBuffer)
        ) {
          data = JSON.stringify(data);
          config.headers = config.headers || {};
          config.headers['Content-Type'] = 'application/json';
        }

        return axios[method](url, data, config).then(responseAdptor);
      },
      updateLocation: (location, replace) => {
        location = normalizeLink(location);
        if (location === 'goBack') {
          return history.goBack();
        } else if (
          (!/^https?\:\/\//.test(location) &&
            location === history.location.pathname + history.location.search) ||
          location === history.location.href
        ) {
          // 目标地址和当前地址一样，不处理，免得重复刷新
          return;
        } else if (/^https?\:\/\//.test(location) || !history) {
          return (window.location.href = location);
        }

        history[replace ? 'replace' : 'push'](location);
      },
      jumpTo: (to, action) => {
        if (to === 'goBack') {
          return history.goBack();
        }

        to = normalizeLink(to);

        if (isCurrentUrl(to)) {
          return;
        }

        if (action && action.actionType === 'url') {
          action.blank === false
            ? (window.location.href = to)
            : window.open(to, '_blank');
          return;
        } else if (action && action.blank) {
          window.open(to, '_blank');
          return;
        }

        if (/^https?:\/\//.test(to)) {
          window.location.href = to;
        } else if (
          (!/^https?\:\/\//.test(to) &&
            to === history.pathname + history.location.search) ||
          to === history.location.href
        ) {
          // do nothing
        } else {
          history.push(to);
        }
      },
      isCurrentUrl: isCurrentUrl,
      theme: 'antd',
    }
  );

  history.listen((state) => {
    amisInstance.updateProps({
      location: state.location || state,
    });
  });
}
initApp();
